package com.dwxt.race.service;

import com.dwxt.common.util.JsonUtils;
import com.dwxt.common.wxpay.MyWXPayConfig;
import com.dwxt.common.wxpay.WXPay;
import com.dwxt.common.wxpay.WXPayUtil;
import com.dwxt.race.dao.RaceMapper;
import com.dwxt.race.dao.RaceOrderMapper;
import com.dwxt.race.dao.UserRaceMapper;
import com.dwxt.race.entity.Race;
import com.dwxt.race.entity.RaceOrder;
import com.dwxt.race.entity.UserRace;
import com.dwxt.race.entity.UserRaceExample;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WxPayService {

    @Autowired
    private RaceOrderMapper raceOrderMapper;
    @Autowired
    private RaceMapper raceMapper;
    @Autowired
    private UserRaceService userRaceService;
    @Autowired
    private UserRaceMapper userRaceMapper;


    @Transactional
    public String payBack(String notifyData) throws Exception {
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        MyWXPayConfig myWXPayConfig = new MyWXPayConfig();
        WXPay wxpay = new WXPay(myWXPayConfig);
        notifyMap = WXPayUtil.xmlToMap(notifyData);         // 转换成map
        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            String return_code = notifyMap.get("return_code");//状态
            String out_trade_no = notifyMap.get("out_trade_no");//订单号
            if (StringUtil.isNotEmpty(out_trade_no)) {
                UserRaceExample userRaceExample = new UserRaceExample();
                UserRaceExample.Criteria criteria = userRaceExample.createCriteria();
                criteria.andOrderIdEqualTo(out_trade_no);
                List<UserRace> userRaces = userRaceMapper.selectByExample(userRaceExample);
                if (userRaces.size() > 0) {
                    UserRace userRace = userRaces.get(0);
                    Integer raceId = userRace.getRaceId();
                    String userId = userRace.getUserId();
                    if (!return_code.equalsIgnoreCase("SUCCESS")) {
                        log.info("微信支付回调失败订单号: {}", notifyMap);
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                                "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                        //库存增加,订单失败
                        raceMapper.updateByPayBack(raceId, 1);
                        //支付失败
                        userRace.setStatus(5);
                        userRaceMapper.updateByPrimaryKeySelective(userRace);
                        return xmlBack;
                    } else {
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" +
                                "<return_msg><![CDATA[SUCCESS]]></return_msg>" + "</xml> ";
                        //更改订单状态
                        RaceOrder raceOrder = new RaceOrder();
                        raceOrder.setUserid(userId);
                        Race race = raceMapper.selectByPrimaryKey(raceId);
                        log.info("race: " + JsonUtils.objectToJson(race));
                        raceOrder.setRealprice(race.getCost());
                        raceOrder.setPaytype(2);
                        raceOrder.setStatus(1);
                        raceOrder.setRaceid(raceId);
                        raceOrder.setId(out_trade_no);
                        //支付成功后生成订单
                        raceOrderMapper.insertSelective(raceOrder);
                        userRace.setStatus(1);
                        userRaceMapper.updateByPrimaryKeySelective(userRace);
                        log.info("微信支付回调成功订单号: {}", notifyMap);
                        return xmlBack;
                    }
                } else {
                    log.info("微信支付回调失败订单号: {}", notifyMap);
                    xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                            "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    return xmlBack;
                }
            } else {
                log.info("微信支付回调失败订单号: {}", notifyMap);
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                        "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } else {
            log.error("微信支付回调通知签名错误");
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return xmlBack;
        }
    }
}
